import 'package:flutter_elf/config/component_index.dart';
import 'package:flutter_elf/utils/common_utils.dart';
import 'package:flutter_elf/widgets/appbar_creator.dart';
import 'package:rxdart/rxdart.dart';
void main(){
  runApp(MaterialApp(
    home: StreamTestPage(),
  ));
}
class StreamTestPage extends BaseWidget{
  @override
  BaseWidgetState<BaseWidget> getState() {
    // TODO: implement getState
    return StreamTestPageState();
  }
}

class StreamTestPageState extends BaseWidgetState{

  Observable timerObservable;

  @override
  void onCreate() {
    // TODO: implement onCreate
    super.onCreate();
    timerObservable = Observable.periodic(Duration(seconds: 2),(i){
      return i.toString();
    });
    timerObservable.listen((data){
      CommonUtils.showToast(data);
    });

    WidgetsBinding.instance.addPostFrameCallback((_){
      _showOverlay(true);
    });

  }

  @override
  Widget buildView(BuildContext context) {
    // TODO: implement buildView
    return Scaffold(
      body: Column(

      ),
    );
  }

  @override
  PreferredSizeWidget initAppbar() {
    // TODO: implement initAppbar
    return AppBarCreator.create(context, 'Stream');
  }
  bool _isShow = false;
  OverlayEntry _overlay;
//触发事件控件的全局key ，通过key可以获取到key对应的控件
  GlobalKey _tapWidget = GlobalKey();
  OverlayEntry _createSelectViewWithContext(BuildContext context){
    //屏幕宽高
    RenderBox  renderBox = context.findRenderObject();
    var screenSize = renderBox.size;
    //触发事件的控件的位置和大小
    renderBox = _tapWidget.currentContext.findRenderObject();
    var parentSize = renderBox.size;
    var parentPosition = renderBox.localToGlobal(Offset.zero);
    //正式创建Overlay
    return OverlayEntry(
        builder: (context) => Positioned (
          top: parentPosition.dy + parentSize.height,
          width: screenSize.width,
          height:screenSize.height-parentPosition.dy-parentPosition.dx,
          child:Stack(
              children:<Widget>[
                GestureDetector(//黑色 26透明度背景
                  onTap:(){
                    setState( () {
                      _isShow = false;
                    });
                    //点击背景 隐藏窗口
                    _showOverlay(_isShow);
                  },
                  child: Container(
                    height: screenSize.height-parentPosition.dy-parentPosition.dx,
                    width:screenSize.width,
                    color:Colors.black26,
                  ),
                ),
                Container( height:100),//悬浮窗口自定义
              ]
          ),
        )
    );
  }

  _showOverlay(bool isShow) {
    if (isShow) {
      _overlay = _createSelectViewWithContext(context);
      Overlay.of(context).insert(_overlay);
    } else {
      _overlay.remove();
    }
  }
}
